#include "cutter.h"


namespace html::tmplt
{

void Cutter::feed(char c) {
    switch (st_) {
    case State::Text:
        if (c != '$') {
            buffer_.push_back(c);
        } else {
            st_ = State::DollarFound;
        }
        break;
    case State::DollarFound:
        if (c != '{') {
            buffer_.push_back('$');
            buffer_.push_back(c);
            st_ = State::Text;
        } else {
            st_ = State::FirstLeftBraceFound;
        }
        break;
    case State::FirstLeftBraceFound:
        if (c != '{') {
            buffer_.push_back('$');
            buffer_.push_back('{');
            buffer_.push_back(c);
            st_ = State::Text;
        } else {
            parts_.add(Part(true, std::move(buffer_)));
            st_ = State::Template;
        }
        break;
    case State::Template:
        if (c != '}') {
            buffer_.push_back(c);
        } else {
            st_ = State::FirstRightBraceFound;
        }
        break;
    case State::FirstRightBraceFound:
        if (c != '}') {
            buffer_.push_back('}');
            st_ = State::Template;
        } else {
            parts_.add(Part(false, std::move(buffer_)));
            st_ = State::Text;
        }
        break;
    default:
        break;
    }
}

void Cutter::stop() {
    if (buffer_.empty()) {
        return;
    }
    switch (st_) {
    case State::Text:
        parts_.add(Part(true, std::move(buffer_)));
        break;
    case State::Template:
        parts_.add(Part(false, std::move(buffer_)));
        break;
    default:
        break;
    }
    st_ = State::Text;
}

} // namespace html::tmplt
